package cn.xzz.pethome.dept.controller;

import cn.xzz.pethome.dept.domain.Department;
import cn.xzz.pethome.dept.query.DeptQuery;
import cn.xzz.pethome.dept.service.IDeptService;
import cn.xzz.pethome.share.utils.AjaxResult;
import cn.xzz.pethome.share.utils.PageCount;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//表示返回值是json数据的controller类
@RestController
@RequestMapping("/dept")
@Api(value = "部门的接口API文档",description = "部门的CRUD功能")
public class DepartmentController {
    @Autowired
    private IDeptService deptService;

    //查询用GetMapping注解
    //@PathVariable参数要写这个
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    public Department Department(@PathVariable("id") @ApiParam(name = "id属性", required = true) Long id) {
           return deptService.findById(id);
    }

    //高级查询和新增
    @PostMapping
    @ApiOperation(value = "部门的高级查询")
    public PageCount<Department> queryDepartment(@RequestBody DeptQuery query){
        System.out.println(deptService.getPageCount(query));
        return  deptService.getPageCount(query);
    }

    //新增和修改
    @PutMapping
    @ApiOperation(value = "新增或者修改,如果id为null就是新增反之修改")
    public AjaxResult Department(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                deptService.adddept(department);
            }else {
                deptService.updatedept(department);
            }
            return AjaxResult.win();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.lose();
        }

    }

    //删除
    @DeleteMapping("/{id}")
    public AjaxResult department(@PathVariable("id") Long id){
        try {
            deptService.delete(id);
            return AjaxResult.win();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.lose();
        }

    }

    @PatchMapping
    @ApiOperation(value = "部门的批量删除" )
    public AjaxResult dept(@RequestBody List<Long> ids){
        try {
            deptService.batchdeletedept(ids);
            return AjaxResult.win();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.lose();
        }
    }

    @GetMapping
    @ApiOperation(value = "查询全部部门")
    public List<Department> deptTree(){

        return  deptService.getTree();
    }
}
